package com.tju.backend.utils.tool;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 判断是否是空的 工具类
 *
 * @USER: CLS
 */
public class EmptyUtils {
    //判空
    public static boolean isEmpty(Object obj) {
        if (obj == null)
            return true;
        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;
        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();
        if (obj instanceof Map)
            return ((Map) obj).isEmpty();
        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (Object o : object) {
                if (!isEmpty(o)) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }


    /**
     * 获取字符的下标返回int
     *
     * @param msg
     * @param s
     * @param i
     * @return
     */
    public static int getCharacterPositionInt(String msg, String s, int i) {
        Matcher slashMatcher = Pattern.compile(s).matcher(msg);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            //当"Z"符号第i次出现的位置
            if (mIdx == i) {
                break;
            }
        }
        return slashMatcher.start();
    }

    /**
     * 读取某个字符在一条字符串下有多少个重复的数据
     *
     * @param msg
     * @param s
     * @return
     */
    public static int seekCharNumber(String msg, char s) {
        int count = 0;
        char[] chars = msg.toCharArray();
        for (char aChar : chars) {
            if (s == aChar) {
                count++;
            }
        }
        return count;
    }


    /**
     * 获取ip的最后一段
     *
     * @param ip
     * @return
     */
    public static String ipFinallyParagraph(String ip) {
        int index = ip.lastIndexOf(".");
        return ip.substring(index + 1);
    }
}
